<?php

namespace plugin\laoha\app\model;

use plugin\laoha\app\model\Cate;
use plugin\laoha\app\model\Comment;
use plugin\admin\app\model\Admin;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\Builder;

class Post extends Base
{
    //use SoftDeletes;

	/**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'ha_posts';

    /**
     * @var array
     */
    protected $increment_fields=['views'];

    protected $casts = [
        'images'=>'json',
        'attaches' => 'json',
        'ext' => 'json',
    ];       

    /**
     * 允许自增自减的字段,无需登录
     */
    protected $add_fields = ['views','goods'];
    protected $acts = ['collect'];

    protected static function booted()
    {      
        static::creating(function ($model) {
            if(config('plugin.laoha.set.app.post.check',0) && !is_manage()){
                $model->status=1;
            }else{
                $model->status=0;
            } 
        });         
        static::saving(function ($model) {
            if(empty($model->admin_id)){
                $model->admin_id = admin_id();
            }
           
            if($images = request()->input('images')){
                $images = str2arr($images);
                $model->cover = $images[0];
            }
            if(empty($model->cover) && $images=self::get_cover_by_content(request()->input('content',''))){
                $model->cover = $images[0];
            }
        });

        static::deleted(function ($model) {
            Comment::where('root_id',$model->id)->where('root','post')->delete();
            AttachUrl::where('root_id',$model->id)->where('root','post')->delete();
            Act::where('root_id',$model->id)->where('root','post')->delete();            
        });    
    }
 
	//从内容中提取图片
	protected static function get_cover_by_content($content=''){
		$pattern='/<img((?!src).)*src[\s]*=[\s]*[\'"]((\/app\/admin\/|\/app\/laoha\/|\/)upload\/(?<src>[^\'"]*))[\'"]/is';
		if(preg_match_all($pattern,$content,$out)){
            return $out[2];
        }else{
            return [];
        }
	}	

    public function data_format($d,$type='list')
    {
        if($type=='list'){
            $d['pos'] = $d['pos']?str2arr($d['pos']):[];
            $d['cover'] = laoha_thumb($d['cover'],300,200);
        }
        return $d;
    }

    public function cate(): BelongsTo
    {
        return $this->belongsTo(Cate::class,'cate_id','id');
    }


    public function admin(): BelongsTo
    {
        return $this->belongsTo(Admin::class,'admin_id','id');
    }

   
    public function comments(): MorphMany
    {
        return $this->morphMany(Comment::class, 'root');
    }  
    public function acts(): MorphMany
    {
        return $this->morphMany(Act::class, 'root');
    }  
 

}
